/**
 * 2015-2016  ()
 */
package com.lw.controller;

import java.util.Random;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;

/**
 * spring-boot-demo-2-1
 * 
 * @author wei.liu
 */
@RestController
@RequestMapping(value = "/api")
public class AnnotationHystrxController {
	private static final Logger LOG = LoggerFactory.getLogger(AnnotationHystrxController.class);

	/**
	 * 参数配置参考：@see http://blog.csdn.net/heyutao007/article/details/51006694
	 * 
	 * @Description:hystrix熔断
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ok", method = RequestMethod.GET)
	@HystrixCommand(fallbackMethod = "okFallback", threadPoolProperties = {
			@HystrixProperty(name = "coreSize", value = "30"), @HystrixProperty(name = "maxQueueSize", value = "100"),
			@HystrixProperty(name = "queueSizeRejectionThreshold", value = "20") }, commandProperties = {
					@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100"),
					@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "50")

	})
	public String ok() throws Exception {
		int l = new Random().nextInt(200);
		LOG.info(String.format("l=%s", l));
		TimeUnit.MILLISECONDS.sleep(l);
		return "ok";
	}

	public String okFallback(Throwable e) {
		System.out.println("execute okFallback!" + e.getMessage());
		LOG.error("error", e);
		return "fallback";
	}

	@RequestMapping(value = "/getUserByIdAsync")
	@HystrixCommand
	public Future<String> getUserByIdAsync() {
		AsyncResult<String> asyncResult = new AsyncResult<String>() {

			@Override
			public String invoke() {
				int t = t();
				int t2 = t2();
				return t + t2 + "";

			}

		};
		System.out.println(555);
		return asyncResult;
	}

	public int t() {
		for (int i = 0; i < 1000; i++) {
			System.out.println("111");
		}
		return 1;
	}

	public int t2() {
		System.out.println("0000000000000");
		return 2;
	}
}
